<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <!-- PageTools 是注册的一个全局组件小卡片 -->
        <PageTools>
          <!-- 插入到left插槽位置 -->
          <template #left>
            <span>总记录数: {{ total }} 条</span>
          </template>
          <!-- 插入到right插槽位置 -->
          <template #right>
            <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
            <el-button type="danger" size="small" @click="handleDownload">导出excel</el-button>
            <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
          </template>
        </PageTools>
      </el-card>
      <el-card style="margin-top: 10px;">
        <!--        它的prop属性指定默认的排序的列 -->

        <el-table border :data="list" :default-sort="{prop: 'workNumber', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- template  -->
            <template #default="{row}">

              {{ EmployeeEnumfuction( row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> query传参 -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hRoles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <empDialog ref="elDialog" @success="hsuccess" />
      </el-dialog>

      <!--// 使用组件  -->

      <el-dialog :visible.sync="showDialogRole">
        <AssignRole v-if="showDialogRole" :roleid="roleid" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getemployeesSimpleList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees' // 默认导出
/* 利用一个空对象来接收数组遍历之后得到的新对象 */
// const hireType = {}
// EmployeeEnum.hireType.forEach((item) => {
//   hireType[item.id] = item.value
// })

//
import AssignRole from './assignRole.vue'

// 也可以使用reduce语法,求和
// 得到一个新对象
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
console.log('hireType', hireType)

//
import empDialog from '@/views/employees/empDialog'
export default {
  components: { empDialog, AssignRole },
  data() {
    return {
      roleid: '',
      showDialogRole: false, // 新增分配角色窗口
      showDialog: false, // 新增弹窗隐藏
      list: [], // 获取的列表
      page: 1, // 当前页数
      size: 10, // 当前条数
      total: 0 // 总共的条数
    }
  },
  created() { this.loadgetemployeesSimple() },
  methods: {
    // 分配角色
    hRoles(id) {
      this.roleid = id
      this.showDialogRole = true
    },
    // 导出函数
    dataFormat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // 先获取表头
      const one = list[0]
      let headers = []
      if (one) {
        console.log(Object.keys(one), 'Object.keys(one)') // 获取
        headers = Object.keys(one).map((enkey) => { // 得到头部
          return mapInfo[enkey]
        })
      }
      // console.log("headers",headers);
      // 2.利用请求头,来循环数组,得到新的
      const data = list.map(item => {
        //
        return Object.values(item)
      })
      // console.log("data",data);
      return { headers, data }
    },

    // 导出
    async handleDownload() {
      // 发送ajax获取
      try {
        const res = await getemployeesSimpleList(this.page, this.size)
        console.log(res)
        if (res.code !== 10000) return // 失败

        // import 用于懒加载(不会一进入就调用,可以调用文件里面的所有参数)
        // then()是可以访问一个pormise对象
        import('@/vendor/Export2Excel').then(excel => {
        // const multiHeader = [['Id', 'Main Information', '', '', 'Date']]
          // const header = ['', 'Title', 'Author', 'Readings', '']
          // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
          // const list = this.list
          // const data = this.formatJson(filterVal, list)
          // const merges = ['A1:A2', 'B1:D1', 'E1:E2']
          const { headers, data } = this.dataFormat(res.data.rows)
          excel.export_json_to_excel({
          // multiHeader,
            header: headers,
            // merges,
            data
          })
        })
      } catch (error) {
        // console.log(error)
        this.$message.error('加载员工列表失败')
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          // return parseTime(v[j])
          return
        } else {
          return v[j]
        }
      }))
    },
    // 删除
    hDel(id) {
      this.$confirm('您确定要删除吗').then(async() => {
        const res = await delEmployee(id)
        console.log('res', res)
        /* 当前列表的数据只剩一条时,减完就-- */
        if (this.list.length === 1) {
          this.page--
          if (this.list.page <= 0) {
            this.page = 1
          }
        }
        this.loadgetemployeesSimple()
      }).catch(err => console.log('', err))
    },

    //
    hClose() {
      this.$refs.elDialog.resetFields()
      this.showDialog = false
    },
    // 新增点击员工
    hAdd() {
      this.showDialog = true
      this.$refs.hAddform.resetFields()
    },
    // 父组件重新渲染,关闭弹层
    hsuccess() {
      // ajax是异步的,所以需要++
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadgetemployeesSimple()
      this.showDialog = false
    },
    //
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadgetemployeesSimple()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadgetemployeesSimple()
    },
    // 枚举
    EmployeeEnumfuction(data) {
      // 需要的是hireType的值
      // find得到的是 判断后的第一个数值
      // 没有改变原数组
      // return EmployeeEnum.hireType.find((item) => { return item.id === data }).value
      return hireType[data] || '未知'
    },
    // 获取员工列表
    async loadgetemployeesSimple() {
      try {
        const res = await getemployeesSimpleList(this.page, this.size)
        console.log(res)
        if (res.code === 10000) {
          this.$message.success('加载员工列表成功')
          this.list = res.data.rows
          this.total = res.data.total
        }
      } catch (error) {
        // console.log(error)
        this.$message.error('加载员工列表失败')
      }
    }
  }
}
</script>
